
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package tp_sd_server.model;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 *
 * @author kill9
 */
public class MapGraph<K,V> implements Serializable{

    private Map<K,Map<K,V>> map;

    public MapGraph() {
        map = new ConcurrentHashMap<K, Map<K, V>>();
    }

    private Map<K,V> generateInitMap(){
        return new ConcurrentHashMap<K, V>();
    }

    public void add(K key){
        map.put(key, generateInitMap());
    }

    public void add(K key,K key2,V value){
        map.get(key).put(key, value);
    }

    public void add(K key,List<K> key2,V value){
        Map<K,V> map = this.map.get(key);
        for(K k : key2){
            map.put(k, value);
        }
    }

    public void remove(K key){
        for(Map<K,V> map : this.map.values()){
            map.remove(key);
        }
        this.map.remove(key);
    }

    public void remove(K key,K key1){
        this.map.get(key).remove(key1);
    }

    public void remove(K key,List<K> key1){
        for(K k : key1){
            remove(key, k);
        }
    }

    public Collection<K> getFollowed(K k){
        return map.get(k).keySet();
    }

    public Collection<K> getFollowers(K k){
        Collection<K> collection = new ArrayList<K>();
        for(Map.Entry<K,Map<K,V>> map : this.map.entrySet()){
            if(map.getValue().containsKey(k)){
                collection.add(map.getKey());
            }
        }
        return collection;
    }
   

    @Override
    public String toString() {
        StringBuilder builder  =  new StringBuilder();
        for(Map.Entry<K,Map<K,V>> entry: this.map.entrySet()){
                builder.append("\n"+entry.getKey()+"\n");
                for(Map.Entry<K,V> entry1  : entry.getValue().entrySet()){
                    builder.append(entry1.getKey()+" "+entry1.getValue());
                    builder.append('\t');

                }
            builder.append('\n');
        }
        return builder.toString();
    }

    public int size(){
        return map.size();
    }


}
